import mongoose from 'mongoose';
import { databaseConfig } from '../config/database.config';

export async function initDatabase() {
  try {
    // 检查是否已经连接
    if (mongoose.connection.readyState === 1) {
      console.log('Already connected to MongoDB');
      return mongoose.connection.db;
    }

    // 连接数据库
    await mongoose.connect(databaseConfig.uri, {
      ...databaseConfig.options
    });
    console.log('Connected to MongoDB');

    // 获取数据库实例
    const db = mongoose.connection.db;

    // 检查并创建集合
    const collections = await db.listCollections().toArray();
    const collectionNames = collections.map(c => c.name);

    if (!collectionNames.includes('workflows')) {
      await db.createCollection('workflows');
      console.log('Created workflows collection');
    }

    if (!collectionNames.includes('presets')) {
      await db.createCollection('presets');
      console.log('Created presets collection');
    }

    return db;
  } catch (error) {
    console.error('Database initialization failed:', error);
    throw error;
  }
} 